package com.kexilo.core.common.aspect;

import com.kexilo.core.common.annotation.DataScope;
import com.kexilo.core.common.constant.UserConstants;
import com.kexilo.core.common.core.domain.BaseEntity;
import com.kexilo.core.common.security.UserPrincipal;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据过滤处理
 * 
 * @author Kexilo
 */
@Aspect
@Component
public class DataScopeAspect {
    
    private static final Logger log = LoggerFactory.getLogger(DataScopeAspect.class);

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DataScope dataScope) {
        // 获取当前的用户
        UserPrincipal loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            // 如果是超级管理员，则不过滤数据
            if (!loginUser.getUserId().equals(1L)) {
                dataScopeFilter(joinPoint, loginUser, dataScope.deptAlias(), dataScope.userAlias());
            }
        }
    }

    /**
     * 数据范围过滤
     * 
     * @param joinPoint 切点
     * @param user 用户
     * @param deptAlias 部门别名
     * @param userAlias 用户别名
     */
    public static void dataScopeFilter(JoinPoint joinPoint, UserPrincipal loginUser, String deptAlias, String userAlias) {
        StringBuilder sqlString = new StringBuilder();
        List<String> conditions = new ArrayList<>();
        
        // 获取用户权限列表
        List<String> rolePermissions = loginUser.getPermissions().stream()
            .filter(perm -> perm.startsWith("data:"))
            .map(perm -> perm.substring(5)) // 去掉 "data:" 前缀
            .toList();

        // 根据权限生成数据权限SQL
        for (String permission : rolePermissions) {
            if (conditions.contains(permission)) {
                continue;
            }
            
            if (UserConstants.DATA_SCOPE_ALL.equals(permission)) {
                // 全部数据权限
                sqlString = new StringBuilder();
                conditions.add(permission);
                break;
            } else if (UserConstants.DATA_SCOPE_CUSTOM.equals(permission)) {
                // 自定义数据权限 - 需要配合角色部门关联表
                if (StringUtils.isNotEmpty(deptAlias)) {
                    sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM kx_sys_role_dept rd INNER JOIN kx_sys_user_role ur ON rd.role_id = ur.role_id WHERE ur.user_id = {} ) ", 
                        deptAlias, loginUser.getUserId()));
                }
            } else if (UserConstants.DATA_SCOPE_DEPT.equals(permission)) {
                // 部门数据权限
                if (StringUtils.isNotEmpty(deptAlias) && StringUtils.isNotNull(loginUser.getDeptId())) {
                    sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, loginUser.getDeptId()));
                }
            } else if (UserConstants.DATA_SCOPE_DEPT_AND_CHILD.equals(permission)) {
                // 部门及以下数据权限
                if (StringUtils.isNotEmpty(deptAlias) && StringUtils.isNotNull(loginUser.getDeptId())) {
                    sqlString.append(StringUtils.format(" OR {}.dept_id IN ( SELECT dept_id FROM kx_sys_dept WHERE dept_id = {} OR ancestors LIKE '%,{},%' )", 
                        deptAlias, loginUser.getDeptId(), loginUser.getDeptId()));
                }
            } else if (UserConstants.DATA_SCOPE_SELF.equals(permission)) {
                // 仅本人数据权限
                if (StringUtils.isNotEmpty(userAlias)) {
                    sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, loginUser.getUserId()));
                } else {
                    // 数据权限为仅本人且没有userAlias别名，不查询任何数据
                    sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
                }
            }
            conditions.add(permission);
        }

        // 如果没有任何数据权限，则限制查询
        if (StringUtils.isEmpty(conditions)) {
            if (StringUtils.isNotEmpty(userAlias)) {
                // 仅查询本人创建的数据
                sqlString.append(StringUtils.format(" AND {}.create_by = '{}' ", userAlias, loginUser.getUsername()));
            } else if (StringUtils.isNotEmpty(deptAlias)) {
                // 限制为不存在的部门ID
                sqlString.append(StringUtils.format(" AND {}.dept_id = 0 ", deptAlias));
            }
        }

        if (StringUtils.isNotEmpty(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                String finalSql = sqlString.toString();
                if (finalSql.startsWith(" OR ")) {
                    finalSql = " AND (" + finalSql.substring(4) + ")";
                }
                baseEntity.getParams().put(UserConstants.DATA_SCOPE, finalSql);
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(UserConstants.DATA_SCOPE, "");
        }
    }
}